package com.fdq.bigevent.service.Imp;

import com.fdq.bigevent.mapper.ArticleMapper;
import com.fdq.bigevent.pojo.Article;
import com.fdq.bigevent.pojo.PageBean;
import com.fdq.bigevent.pojo.Result;
import com.fdq.bigevent.service.ArticleService;
import com.fdq.bigevent.util.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class ArticleServiceImp implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public Result addArticle(Article article) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);
        if(articleMapper.addArticle(article) == 1){
            return Result.success();
        }else {
            return Result.error("增加文章出错");
        }
    }

    @Override
    public Result<PageBean> getArticle(int pageNum, int pageSize, int categoryId, String state) {
        //创建pageBean对象
        PageBean<Article> pb = new PageBean<>();
        //开启分页查询  PageHelper
        PageHelper.startPage(pageNum,pageSize);
        //调用mapper
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> articles = articleMapper.selectArticle(categoryId,state,userId);
        //将查询的结果封装为Page对象获取总结果数与当前页内容
        Page<Article> articlePage = (Page<Article>) articles;
        //将数据填充到pageBean中
        pb.setTotal(articlePage.getTotal());
        pb.setItems(articlePage.getResult());
        return Result.success(pb);
    }

    @Override
    public Result<Article> getArticleById(Integer id) {
        Article article = articleMapper.selectArticleById(id);
        if(article == null){
            return Result.error("该文章不存在");
        }else {
            return Result.success(article);
        }
    }

    @Override
    public Result updateArticle(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        if(articleMapper.updateArticle(article) == 1){
            return Result.success();
        }else {
            return Result.error("更新文章出错");
        }

    }

    @Override
    public Result deleteArticle(Integer id) {
        if(articleMapper.deleteArticle(id) == 1){
            return Result.success();
        }else {
            return Result.error("删除文章出错");
        }
    }
}
